package com.sanjiahantang.youjiaclient.module.me.address.presenters;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.CheckBox;

import com.sanjiahantang.plugin.pickerview.OptionsPickerView;
import com.sanjiahantang.uilibrary.adapter.listview.BaseAdapterHelper;
import com.sanjiahantang.uilibrary.adapter.listview.QuickAdapter;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.R;
import com.sanjiahantang.youjiaclient.base.BaseBean;
import com.sanjiahantang.youjiaclient.base.BaseMvpPresenter;
import com.sanjiahantang.youjiaclient.base.BaseView;
import com.sanjiahantang.youjiaclient.base.CallBack;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.SPConfig;
import com.sanjiahantang.youjiaclient.module.city.models.ICityModel;
import com.sanjiahantang.youjiaclient.module.city.models.impl.CityModel;
import com.sanjiahantang.youjiaclient.module.common.models.IUserModel;
import com.sanjiahantang.youjiaclient.module.common.models.impl.UserModel;
import com.sanjiahantang.youjiaclient.module.login.views.impl.LoginActivity;
import com.sanjiahantang.youjiaclient.module.me.address.beans.AddressBean;
import com.sanjiahantang.youjiaclient.module.me.address.beans.AddressDetailBean;
import com.sanjiahantang.youjiaclient.module.me.address.views.AddressView;
import com.sanjiahantang.youjiaclient.module.me.address.views.impl.AddressActivity;
import com.sanjiahantang.youjiaclient.module.programmeprice.views.impl.ProgramChoiceInfoActivity;
import com.sanjiahantang.youjiaclient.utils.SPUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import static android.app.Activity.RESULT_OK;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_PHONE;
import static com.sanjiahantang.youjiaclient.config.StaticValue.KEY_TOKEN;
import static com.sanjiahantang.youjiaclient.config.StaticValue.RESPONSE_CODE_SUC;

/**
 * Created by zy on 2017/9/22.
 */
public class AddressPresenter extends BaseMvpPresenter<AddressView> {

    private QuickAdapter<AddressBean.Data> quickAdapter;
    private IUserModel userModel;
    private ICityModel cityModel;
    private AddressView.OnDetailLoadListener onDetailLoadListener;
    private OptionsPickerView pvOptionsDialog;

    private ArrayList<String> listProvince;
    private ArrayList<ArrayList<String>> listCity;
    private ArrayList<ArrayList<ArrayList<String>>> listArea;

    public AddressPresenter() {
        userModel = new UserModel();
        cityModel = new CityModel();
    }


    public void onPostResume(Context context) {
        onPostResume(context,null);
    }

    public void onPostResume(Context context, final BaseView.OnLoadListener listener) {
        mView.showProgress();
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        userModel.getAddressList(context, params, new CallBack<AddressBean>(){

            @Override
            public void onSuccess(AddressBean response, Context context, Object tag) {
                mView.hideProgress();
                if (response != null && response.getCode() == RESPONSE_CODE_SUC) {
                    quickAdapter.clear();
                    if (listener != null){
                        listener.onLoad(response.getData().size());
                    }
                    if (response.getData().size() > 0) {
                        quickAdapter.addAll(response.getData());
                    } else
                        Utils.showToast(context, response.getMessage());
                } else if (response.getCode() == RESPONSE_CODE_SUC) {
                    LoginActivity.logout(context);
                    Utils.showToast(context, response.getMessage());
                }
            }

            @Override
            public void onFailure(String message) {
                mView.hideProgress();
            }
        });
    }

    public void initAdapter(Context context, AddressView.OnLoadListener onLoadListener) {
        if (quickAdapter == null) {
            quickAdapter = new QuickAdapter<AddressBean.Data>(context, R.layout.item_address) {
                @Override
                protected void convert(final BaseAdapterHelper helper, final AddressBean.Data item) {
                    helper.setText(R.id.txtName, item.getCustomerName());
                    helper.setText(R.id.txtPhone, item.getCellPhone().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
                    helper.setText(R.id.txtAddress, item.getFullAddress());
                    //删除
                    helper.setOnClickListener(R.id.txtDelete, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Utils.showDialog((Activity) context, "提示", "确定要删除地址吗？", "", "", new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    Utils.dismissDialog();
                                    switch (view.getId()) {
                                        case R.id.txtDialogCancel:
                                            break;
                                        case R.id.txtDialogSure:
                                            loadDelete(context, item.getUcaId());
                                            break;
                                    }
                                }
                            });
                        }
                    });
                    //编辑
                    helper.setOnClickListener(R.id.txtEdit, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent itEdit = new Intent(context, AddressActivity.class);
                            itEdit.putExtra("address", item.getUcaId());
                            context.startActivity(itEdit);
                        }
                    });
                    //设置默认地址
                    helper.setOnClickListener(R.id.defaultAddress, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            CheckBox checkBox = helper.getView(R.id.checkBox);
                            if (!checkBox.isChecked()){
                                editDefault(context, item.getUcaId(), 1);
                            }
                        }
                    });

                    boolean check = false;
                    if (item.getIsDefault() == 1)
                        check = true;
                    helper.setChecked(R.id.checkBox, check);
                }
            };
        }
        onLoadListener.initList(quickAdapter);
    }

    private void editDefault(Context context, int ucaId, int isDefault) {
        mView.showProgress();
        Map<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID, ucaId);
        params.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());

        params.put(AddressView.KEY_PHONE, "");
        params.put(AddressView.KEY_NAME, "");
        params.put(AddressView.KEY_ADDRESS, "");
        params.put(AddressView.KEY_FULL_ADDRESS, "");
        params.put(AddressView.KEY_IS_DEFAULT, String.valueOf(isDefault));
        userModel.editDefaultAddress(context, params, new EditDefaultCallBack());
    }

    private void loadDelete(Context context, int id) {
        mView.showProgress();
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID, String.valueOf(id));
        userModel.deleteAddress(context, params, new DeleteAddressCallBack());
    }

    public void addNewAddress(Context context,int type) {
        ((Activity)context).startActivityForResult(new Intent(context, AddressActivity.class)
            .putExtra(KEY_TYPE,type),0xaa
        );
    }

    public void loadAddress(Context context, String id, AddressView.OnDetailLoadListener onDetailLoadListener) {
        this.onDetailLoadListener = onDetailLoadListener;
        Map<String, String> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID, id);
        hideProgress();
        userModel.loadAddressDetail(context, params, new LoadAddressDetailCallBack());
    }

    /**
     * @param context
     * @param customerName
     * @param fullAddress
     * @param cellPhone
     * @param id           token
     *                     query	string
     *                     ucaId
     *                     地址Id
     *                     query	long
     *                     phone
     *                     客户账号
     *                     query	string
     *                     cellPhone
     *                     手机号
     *                     query	string
     *                     customerName
     *                     收货人姓名
     *                     query	string
     *                     address
     *                     所在地
     *                     query	string
     *                     fullAddress
     *                     详细地址
     *                     query	string
     *                     isDefault
     */
    public void saveAddress(final Context context, String customerName, String fullAddress, String cellPhone, String address, String id, int isDefault, final int type) {

        Map<String, Object> params = new HashMap<>();
        params.put(KEY_TOKEN, ConfigValue.DATA_KEY);
        params.put(AddressView.KEY_ID, id);
        params.put(KEY_PHONE, SPUtils.get(context, SPConfig.PHONE, "").toString());
        params.put(AddressView.KEY_PHONE, cellPhone);
        params.put(AddressView.KEY_NAME, customerName);
        params.put(AddressView.KEY_ADDRESS, address);
        params.put(AddressView.KEY_FULL_ADDRESS, fullAddress);
        params.put(AddressView.KEY_IS_DEFAULT, String.valueOf(isDefault));
        mView.showProgress();
        userModel.saveAddress(context, params, new CallBack<BaseBean>() {

            @Override
            public void onSuccess(BaseBean response, Context context, Object tag) {
                hideProgress();
                if (response.getCode() == RESPONSE_CODE_SUC) {
                    if (type == 0){
                        ((Activity)context).setResult(Activity.RESULT_OK);
                    }
                    ((Activity) context).finish();
                    Utils.showToast(context, response.getMessage());
                } else if (response.getCode() == RESPONSE_CODE_SUC) {
                    LoginActivity.logout(context);
                }
                Utils.showToast(context, response.getMessage());
            }

            @Override
            public void onFailure(String message) {
                hideProgress();
                Utils.showToast(context, message);
            }
        });
    }
//    public void showCityDialog(Context context) {
//        if(listProvince != null && listProvince.size() > 0){
//            pvOptionsDialog.show();
//        }
//    }

//    private void initPickView(Context context){
//        if(pvOptionsDialog == null){
//            pvOptionsDialog = new OptionsPickerView.Builder(context, new OptionsPickerView.OnOptionsSelectListener() {
//                @Override
//                public void onOptionsSelect(int options1, int options2, int options3, View v) {
//                    //返回的分别是三个级别的选中位置
//                    if(onDetailLoadListener != null){
//                        String tx = listProvince.get(options1) + "-"
//                                + listCity.get(options1).get(options2) + "-"
//                                + listArea.get(options1).get(options2).get(options3);
//                        onDetailLoadListener.setLocate(tx);
//                    }
//
//                }
//            })
//
//                    .setTitleText("")
//                    .setDividerColor(Color.BLACK)
//                    .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
//                    .setContentTextSize(20)
//                    .build();
//            initAreaOptions(context);
//        }
//    }
//
//    private void initAreaOptions(Context context) {
//        //选项选择器
//        // 初始化三个列表数据
//        listProvince = new ArrayList<>();
//        listCity = new ArrayList<>();
//        listArea = new ArrayList<>();
//        cityModel.getAllArea(context,listProvince,listCity,listArea,new CityDataCallBack());
//    }


//
//    public void setOnDetailLoadListener(Context context, AddressView.OnDetailLoadListener onDetailLoadListener) {
//        this.onDetailLoadListener = onDetailLoadListener;
//        initPickView(context);
//    }

    public boolean onBackPressed() {
        if (pvOptionsDialog != null && pvOptionsDialog.isShowing()) {
            pvOptionsDialog.dismiss();
            return true;
        }
        return false;
    }



    private class DeleteAddressCallBack implements CallBack<BaseBean> {

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            mView.hideProgress();
            if (response.getCode() == RESPONSE_CODE_SUC)
                onPostResume(context);
            else if (response.getCode() == RESPONSE_CODE_SUC) {
                LoginActivity.logout(context);
            }
            Utils.showToast(context, response.getMessage());
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }

    //三级联动
    public void loadPersonCityList(Context context, BaseView.OnLoadListener listener) {
        cityModel.getAllArea(context, listener);
    }

    private class EditDefaultCallBack implements CallBack<BaseBean> {

        @Override
        public void onSuccess(BaseBean response, Context context, Object tag) {
            mView.hideProgress();
            if (response.getCode() == RESPONSE_CODE_SUC)
                onPostResume(context);
            else if (response.getCode() == RESPONSE_CODE_SUC) {
                LoginActivity.logout(context);
            }
            Utils.showToast(context, response.getMessage());
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }


    private void hideProgress() {
        if (mView != null) {
            mView.showProgress();
        }
    }

    private class LoadAddressDetailCallBack implements CallBack<AddressDetailBean> {

        @Override
        public void onSuccess(AddressDetailBean response, Context context, Object tag) {
            mView.hideProgress();
            onDetailLoadListener.loadData(response);
            //initPickView(context);
        }

        @Override
        public void onFailure(String message) {
            mView.hideProgress();
        }
    }

}
